<template>
  <span>{{ displayValue }}</span>
</template>

<script setup name="IMask">
import { computed } from 'vue'
import { useMaskStore } from '@/stores/mask'

const maskStore = useMaskStore()

const props = defineProps({
  value: {
    type: String,
    required: true
  },
  type: {
    type: String,
    default: 'name',
    validator: (value) => {
      return ['name', 'phone', 'email', 'idcard', 'bankCard', 'custom'].includes(value)
    }
  },
  pattern: {
    type: Object,
    default: () => ({
      start: 0,
      end: 0,
      mask: '*'
    })
  }
})

// 根据全局状态决定是否显示完整值
const displayValue = computed(() => {
  return maskStore.showFullValue ? props.value : maskedValue.value
})

const maskedValue = computed(() => {
  if (!props.value) return ''

  switch (props.type) {
    case 'name':
      return maskName(props.value)
    case 'phone':
      return maskPhone(props.value)
    case 'email':
      return maskEmail(props.value)
    case 'idcard':
      return maskIDCard(props.value)
    case 'bankCard':
      return maskBankCard(props.value)
    case 'custom':
      return maskCustom(props.value, props.pattern)
    default:
      return props.value
  }
})

// 姓名脱敏：保留姓，其他用*代替
const maskName = (value) => {
  if (value.length <= 1) return value
  return value.charAt(0) + '*'.repeat(value.length - 1)
}

// 手机号脱敏：保留前3后4，中间用*代替
const maskPhone = (value) => {
  return value.replace(/(\d{3})\d*(\d{4})/, '$1****$2')
}

// 邮箱脱敏：@前半部分只显示第一个字符和最后一个字符，中间用*代替
const maskEmail = (value) => {
  const [username, domain] = value.split('@')
  if (!domain) return value

  if (username.length <= 2) {
    return username + '@' + domain
  }

  return (
    username.charAt(0) +
    '*'.repeat(username.length - 2) +
    username.charAt(username.length - 1) +
    '@' +
    domain
  )
}

// 身份证号脱敏：保留前4后4，中间用*代替
const maskIDCard = (value) => {
  return value.replace(/(\d{4})\d*(\d{4})/, '$1********$2')
}

// 银行卡号脱敏：保留后4位，其他用*代替
const maskBankCard = (value) => {
  return '*'.repeat(value.length - 4) + value.slice(-4)
}

// 自定义脱敏规则
const maskCustom = (value, pattern) => {
  const { start = 0, end = 0, mask = '*' } = pattern
  if (value.length <= start + end) return value

  return value.slice(0, start) + mask.repeat(value.length - start - end) + value.slice(-end)
}
</script>

<style scoped>
</style> 